package com.work.simpleoa.util;

import com.work.simpleoa.entities.MyTemplate;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * Created by lanli on 2017/4/7.
 */
public class BeetlUtils {

    private static final Logger log = LoggerFactory.getLogger(BeetlUtils.class);


//    public static void main(String[] args){
//
//        try{
//            //ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader();
//            //boolean exist = classpathResourceLoader.exist("myBeetl.properties");
//            //log.info("当前对象是否存在:{}",exist);
//            MyTemplate myTemplate = new MyTemplate();
//            String dir = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
//            String fileName = "myBeetl.properties";
//            Properties properties = new Properties();
//            properties.load(new FileInputStream(dir + fileName));
//           // properties.load(dir);
//            /*
//            设置公共属性：实体类名，模块包名
//             */
//            myTemplate.setRootPath(properties.getProperty("RootPath"));
//            myTemplate.setRootPackageName(properties.getProperty("RootPackageName"));
//            myTemplate.setEntityClassName(properties.getProperty("EntityClassName"));
//            myTemplate.setEntityName(properties.getProperty("EntityName"));
//            myTemplate.setPackageName(properties.getProperty("PackageName"));
//
//            /*
//            设置Entity属性，生成Entity
//             */
//            myTemplate.setCollectionName(properties.getProperty("CollectionName"));
//           /* myTemplate.setList(getMongFieldList(properties.getProperty("SqlFile")));*/
//            myTemplate.setTemplateName("entity.btl");
//            createEntity(myTemplate);
//
//            /*
//            生成DAO
//             */
//            createDaoInterface(myTemplate);
//            myTemplate.setTemplateName("dao.btl");
//            createDaoClass(myTemplate);
//
//            /*
//             生成Service
//             */
//            createServiceInterface(myTemplate);
//            myTemplate.setTemplateName("service.btl");
//            createServiceClass(myTemplate);
//
//            /*
//            设置Controller属性，生成Controller
//             */
//            myTemplate.setPackageMapPath();
//            myTemplate.setTemplateName("Controller.btl");
//            createController(myTemplate);
//        }catch(Exception e){
//            e.printStackTrace();
//        }
//    }


    public void loadGenCodeProperties(String loadPath,Boolean isload){
        //TODO 区分是否为相对路径还是绝对路径,相对路径就从先锋队路径中查找
    }

    public static Boolean genCode(){
        try{
            //ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader();
            //boolean exist = classpathResourceLoader.exist("myBeetl.properties");
            //log.info("当前对象是否存在:{}",exist);
            MyTemplate myTemplate = new MyTemplate();
            String dir = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
            String fileName = "myBeetl.properties";
            Properties properties = new Properties();
            properties.load(new FileInputStream(dir + fileName));
            // properties.load(dir);
            /*
            设置公共属性：实体类名，模块包名
             */
            myTemplate.setRootPath(properties.getProperty("RootPath"));
            myTemplate.setRootPackageName(properties.getProperty("RootPackageName"));
            myTemplate.setEntityClassName(properties.getProperty("EntityClassName"));
            myTemplate.setEntityName(properties.getProperty("EntityName"));
            myTemplate.setPackageName(properties.getProperty("PackageName"));

            /*
            设置Entity属性，生成Entity
             */
            myTemplate.setCollectionName(properties.getProperty("CollectionName"));
            /* myTemplate.setList(getMongFieldList(properties.getProperty("SqlFile")));*/
            myTemplate.setTemplateName("entity.btl");
            createEntity(myTemplate);

            /*
            生成DAO
             */
            createDaoInterface(myTemplate);
            myTemplate.setTemplateName("dao.btl");
            createDaoClass(myTemplate);

            /*
             生成Service
             */
            createServiceInterface(myTemplate);
            myTemplate.setTemplateName("service.btl");
            createServiceClass(myTemplate);

            /*
            设置Controller属性，生成Controller
             */
            myTemplate.setPackageMapPath();
            myTemplate.setTemplateName("Controller.btl");
            createController(myTemplate);
        }catch(Exception e){
            e.printStackTrace();
            return Boolean.valueOf(false);
        }
        return Boolean.valueOf(true);
    }


    public static void createController(MyTemplate myTemplate){
        String filePath = myTemplate.getPackagePath() + "controller";
        String fileName = myTemplate.getEntityClassName() + "Controller.java";
        createJavaFile(myTemplate,filePath,fileName);
    }
    public static void createEntity(MyTemplate myTemplate){
        String filePath = myTemplate.getPackagePath() + "entity";
        String fileName = myTemplate.getEntityClassName() + ".java";
        createJavaFile(myTemplate,filePath,fileName);
    }
    public static void createServiceClass(MyTemplate myTemplate){
        String filePath = myTemplate.getPackagePath() + "service" + File.separator + "impl";
        String fileName = myTemplate.getEntityClassName() + "ServiceImpl.java";
        createJavaFile(myTemplate,filePath,fileName);
    }
    public static void createServiceInterface(MyTemplate myTemplate){
        String filePath = myTemplate.getPackagePath() + "service";

        String fileName = "I" + myTemplate.getEntityClassName() + "Service.java";
        createJavaFile(myTemplate,filePath,fileName);
    }
    public static void createDaoClass(MyTemplate myTemplate){
        String filePath = myTemplate.getPackagePath() + "dao" + File.separator + "impl";
        String fileName = myTemplate.getEntityClassName() + "DaoImpl.java";
        createJavaFile(myTemplate,filePath,fileName);
    }
    public static void createDaoInterface(MyTemplate myTemplate){
        String filePath = myTemplate.getPackagePath() + "dao";
        String fileName = "I" + myTemplate.getEntityClassName() + "Dao.java";
        createJavaFile(myTemplate,filePath,fileName);
    }

    public static void createJavaFile(MyTemplate myTemplate,String filePath,String fileName){
        try{
            //指定模板路径
            String root = System.getProperty("user.dir") + File.separator + File.separator + "src" + File.separator + "main"
                    + File.separator + "resources" + File.separator + "templates" + File.separator;
            FileResourceLoader resourceLoader = new FileResourceLoader(root,"utf-8");
            Configuration cfg = Configuration.defaultConfiguration();
            GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
            //指定要加载的模板
            Template t = gt.getTemplate(myTemplate.getTemplateName());
            //绑定全局变量
            t.binding("myUtil",myTemplate);
            //读取模板输出的文本
            String str = t.render();
            System.out.println(str);
            File dir = new File(myTemplate.getRootPath() + File.separator + filePath);
            System.out.println("生成文件存放的文件夹信息为:"+dir);
            if(!dir.exists() && !dir.isDirectory()){
                dir.mkdirs();
                System.out.println("生成文件存放的文件夹信息为:"+dir);
            }
            File file = new File( dir + File.separator + fileName );
            System.out.println("生成文件的信息为:"+file);
            if(!file.exists()){
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(str);
            bw.flush();
            bw.close();
            System.out.println("当前实体类文件生成路径信息为:"+(filePath+fileName));
        }catch(Exception e){
            System.out.println(e.getMessage());
        }

    }

//    public static List<MongoFields> getMongFieldList(String fileName) throws Exception{
//        List<MongoFields> mongoFieldsList = new ArrayList<MongoFields>();
//        ObjectMapper objectMapper = new ObjectMapper();
//        List<Map<String,Object>> list = (List<Map<String,Object>>)objectMapper.readValue(new FileInputStream(System.getProperty("user.dir") + File.separator + "sql" + File.separator + fileName), List.class);
//        for(Map<String,Object> map : list){
//            MongoFields mongoFields = new MongoFields();
//            mongoFields.setName(map.get("name").toString());
//            mongoFields.setType(map.get("type").toString());
//            mongoFields.setNull((Boolean) map.get("isNull"));
//            mongoFields.setIndex((Boolean)map.get("isIndex"));
//            mongoFields.setDefaultValue(map.get("defaultValue"));
//            if(map.get("description") != null)
//            mongoFields.setDescription(map.get("description").toString());
//            mongoFieldsList.add(mongoFields);
//        }
//        return mongoFieldsList;
//    }
}
